﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Globalization;
using System.Resources;
using System.Reflection;
using System.Diagnostics;
using System.IO;
using Utility.LoggingService;
using com.calitha.goldparser;
using System.CodeDom;
using Microsoft.CSharp;
using Microsoft.VisualBasic;
using System.CodeDom.Compiler;
using System.Collections;


namespace _0512063_0512082
{
    
    public partial class MainForm : Form
    {
        public struct Language
        {
            public String text;
            public CodeDomProvider provider;
            

            public Language(String a, CodeDomProvider b)
            {
                text = a;
                provider = b;
            }
        }
        private String strResourcesPath = Application.StartupPath + "/resource";
        private String strCulture = "es-ES";
        private static ResourceManager rm;
        private CodeMemberMethod method;
        private CodeRunner runner;
        private SampleLoader sampleLoader;
        
        public static ResourceManager RM
        {
            get { return rm; }
        }
        public MainForm()
        {
            InitializeComponent();
            rtbKetqua.ConfigurationManager.Language = "cs";
            strCulture = RegistryUtil.GetStringRegistryValue(@"Language", "es-ES");
            sampleLoader = new SampleLoader();
            loadExample();
        }

        private void loadExample(){
            String[] names = sampleLoader.getSampleName();
            for(int i = 0 ; i < names.Length; i++)
            {
                ToolStripMenuItem tsmi = new ToolStripMenuItem(names[i]);
                tsmi.Click += new EventHandler(Example_Click);
                menuExample.DropDownItems.Insert(0,tsmi);
            }
        }

        private void Example_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem tsmi = (ToolStripMenuItem)sender;
            rtbDacta.Text = sampleLoader.getSample(tsmi.Text);
        }

        public void setCulture(String strCulture)
        {
            CultureInfo objCI = new CultureInfo(strCulture);
            Thread.CurrentThread.CurrentCulture = objCI;
            Thread.CurrentThread.CurrentUICulture = objCI;
        }

        public void setResource()
        {
            rm = ResourceManager.CreateFileBasedResourceManager
                ("resource", strResourcesPath, null);
            try
            {
                menuFile.Text = rm.GetString("menuFile");
                menuBar.Text = rm.GetString("menuEdit");
                menuLang.Text = rm.GetString("menuLang");
                menuHelp.Text = rm.GetString("menuHelp");
                menuItemAbout.Text = rm.GetString("menuItemAbout");
                menuTool.Text = rm.GetString("menuTool");
                menuItemGenCode.Text = rm.GetString("menuItemGenCode");
                menuItemCompile.Text = rm.GetString("menuItemCompile");
                menuItemCompileRun.Text = rm.GetString("menuItemCompileRun");
                menuExample.Text = rm.GetString("menuExample");
                this.Text = rm.GetString("appTitle");
                menuItemExit.Text = rm.GetString("menuItemExit");
                menuItemVietNam.Text = rm.GetString("menuItemVietNam");
                menuItemEnglish.Text = rm.GetString("menuItemEnglish");
                btnRun.Text = rm.GetString("btnRun");
                btnGen.Text = rm.GetString("btnGen");
                choiceLang.Text = rm.GetString("choiceLang");                
                itemShowLogfile.Text = rm.GetString("showlogfile");

            }
            catch (Exception exc) { CLogger.WriteLog(ELogLevel.ERROR, exc.Message); }
        }

        private void eng_Click(object sender, EventArgs e)
        {
            strCulture ="es-ES";
            setUIChange();
        }

        private void vie_Click(object sender, EventArgs e)
        {
            strCulture = "vi-VN";
            setUIChange();
        }

        public void setUIChange()
        {
            try
            {
                RegistryUtil.SetStringRegistryValue("Language", strCulture);
                setCulture(strCulture);
                setResource();
            }
            catch (Exception exc) { CLogger.WriteLog(ELogLevel.ERROR, exc.Message); }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            setUIChange();
            cbLanguage.Items.AddRange(new String[] { "C#", "VB.NET" });
            cbLanguage.SelectedIndex = 0;
        }

        private void menuItemAbout_Click(object sender, EventArgs e)
        {
            About aboutfrm = new About();
            aboutfrm.ShowDialog();
        }

        /// <summary>
        /// Nút nhấn phát sinh code
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        MyParser parser;
        private void btnGen_Click(object sender, EventArgs e)
        {
            GenCode();
        }

        public void GenCode()
        {
            
            if (rtbDacta.Text.Trim().Equals(String.Empty))
                Utilities.showStopMessage(rm.GetString("funcDacTaReq"));
            try
            {
                parser = new MyParser("Grammar_v1e.cgt");
                method = (System.CodeDom.CodeMemberMethod)parser.Parse(rtbDacta.Text);
                if (method != null)
                {
                    NetCodeGenerator ncg = new NetCodeGenerator(method, getProvider());
                    String code = (String)ncg.start();

                    if (Utilities.showComfirmMessage(RM.GetString("SaveCode"), RM.GetString("ConfirmSaveCode")) == DialogResult.OK)
                    {
                        String filePath = Utilities.openSaveDialog(cbLanguage.Text, rtbKetqua.ConfigurationManager.Language);
                        GenCodeFile.Text = filePath;
                        if (filePath.Equals(String.Empty))
                            Utilities.showNormalMessage(RM.GetString("GenCodeNotSave"));
                        else
                        {
                            FileUtil.WriteFile(code, filePath);
                        }
                    }
                    rtbKetqua.Text = code;
                }
            }
            catch (Exception ex)
            {
                CLogger.WriteLog(ELogLevel.ERROR, ex.Message);
            }
        }

        public CodeDomProvider getProvider()
        {
            if (cbLanguage.Text.ToLower().Equals("c#"))
            {
                return new CSharpCodeProvider();
            }
            else if (cbLanguage.Text.ToLower().Equals("vb.net"))
                return new VBCodeProvider();
            return null;
                
        }

        private void cbLanguage_SelectedIndexChanged(object sender, EventArgs e)
        {
            String selectedLang = (String)cbLanguage.SelectedItem;
            if(selectedLang == "C#")
            {
                rtbKetqua.ConfigurationManager.Language = "cs";
            }
            else if(selectedLang == "VB.NET")
            {
                rtbKetqua.ConfigurationManager.Language = "vb";
            }
        }

        /// <summary>
        /// Nhấn nút run: thực hiện compile và run chưa trình
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRun_Click(object sender, EventArgs e)
        {
            CompileCode();
            if (runner.CanExecute)
                runner.Run();
        }

        private void CompileCode()
        {
            if (rtbKetqua.Text.Trim().Equals(string.Empty))
                return;

            //String des = Utilities.openSaveDialog("Excutable", "exe");
            //if (!des.Equals(String.Empty))
            //{
                
                    try
                    {
                        runner = new CodeRunner(getProvider(), rtbKetqua.Text, method.Name + ".exe");
                        String error = runner.Compile();
                        Utilities.showNormalMessage(error);
                    }
                    catch (Exception ex)
                    {
                        CLogger.WriteLog(ELogLevel.ERROR, ex.Message);
                        Utilities.showErrorMessage(ex.Message);
                    }
                
            //}
        }

        private void saveCode_Click(object sender, EventArgs e)
        {
            if (rtbKetqua.Text.Trim().Equals(String.Empty))
            {
                return;
            }
            String filepath = Utilities.openSaveDialog(cbLanguage.Text, rtbKetqua.ConfigurationManager.Language);
            if (!filepath.Equals(String.Empty))
                FileUtil.WriteFile(rtbKetqua.Text, filepath);
        }

        private void menuItemGenCode_Click(object sender, EventArgs e)
        {
            GenCode();
        }

        private void menuItemExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void itemShowLogfile_Click(object sender, EventArgs e)
        {
            Process myProcess = new Process();

            try
            {                
                myProcess.StartInfo.FileName = "AppLog\\ApplicationLog.log";                
                myProcess.StartInfo.CreateNoWindow = true;
                myProcess.Start();
            }
            catch (Win32Exception ex)
            {
                if (ex.NativeErrorCode == 2)
                {
                    Utilities.showErrorMessage(RM.GetString("Filenotfound"));
                }
            }
        }

        private void toolBar_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {            
            rtbDacta.AppendText(e.ClickedItem.Tag.ToString());           
        }

        private void menuItemCompile_Click(object sender, EventArgs e)
        {
            CompileCode();
        }

        private void menuItemCompileRun_Click(object sender, EventArgs e)
        {
            CompileCode();
            if(runner.CanExecute)
                runner.Run();
        }

        private void saveExampleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
        }

        private void openExampleFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
           
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            SampleSave ss = new SampleSave(rtbDacta.Text);
            Boolean choice = ss.ShowSaveDialog(this);
            if (choice)
            {
                String[] newExs = sampleLoader.loadAllSamples();
                for (int i = 0; i < newExs.Length; i++)
                {
                    ToolStripMenuItem tsmi = new ToolStripMenuItem(newExs[i]);
                    tsmi.Click += new EventHandler(Example_Click);
                    menuExample.DropDownItems.Insert(0, tsmi);
                }
            }

        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            Process.Start(sampleLoader.SampleFolderPath);
        }
    }
}
